package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: gulimall
 * @description: TODO
 * @author: YuWenYi
 * @create: 2021-07-16 10:03
 **/
@Controller
public class HelloController {
    /**
     * 无需登录就可访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping(value = "/employees")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token", required = false) String token) {

        if (!StringUtils.isEmpty(token)){
            //利用token从服务器获取用户信息,然后保存到session中
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String userInfo = forEntity.getBody();
            session.setAttribute("loginUser", userInfo);
        }

        //需要sso服务保存一个session
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null){
            //没登录,跳转到sso服务器去进行登录操作

            return "redirect:http://ssoserver.com:8080/login.html?redirect_url=http://client1.com:8081/employees";
        }
        List<String> emps = new ArrayList<>();
        emps.add("张三");
        emps.add("李四");

        model.addAttribute("emps", emps);

        return "employees";
    }

}